const querystring = require('querystring');
const handlerBlogRouter = require('./src/router/blog');
const handlerUserRouter = require('./src/router/user');
const { handlerCookie, getPostData } = require('./src/utils/index');
const { getCookieExpires } = require('./src/utils/index');
const { get, set } = require('./src/db/redis');
const { access } = require('./src/utils/log');

// session 数据
const SESSION_DATA = {};

const serverHandle = (req, res) => {
  // 记录访问日志 access.log
  access(req);

  // 设置返回格式为JSON
  res.setHeader('Content-type', 'application/json');

  const method = req.method;
  const url = req.url;
  // 解析 path
  req.path = url.split('?')[0];
  // 解析 query
  req.query = querystring.parse(url.split('?')[1]);
  // 解析 cookie
  const cookieString = req.headers.cookie || '';
  req.cookie = handlerCookie(cookieString);
  // 解析 session
  let needSetCookie = false;
  let userId = req.cookie.userId;
  // if (userId) {
  //   if (!SESSION_DATA[userId]) {
  //     SESSION_DATA[userId] = {};
  //   }
  // } else {
  //   needSetCookie = true;
  //   userId = Date.now() + '';
  //   SESSION_DATA[userId] = {};
  // }
  // req.session = SESSION_DATA[userId];
  if (!userId) {
    needSetCookie = true;
    userId = Date.now() + '';
    // 初始化 redis 中的 session
    set(userId, {});
  }
  // 获取 session
  req.sessionId = userId;
  get(req.sessionId)
    .then(sessionData => {
      if (sessionData === null) {
        // 初始化 redis 中的 session
        set(req.sessionId, {});
        // 设置 session 
        req.session = {};
      } else {
        req.session = sessionData;
      }
      // 处理 postData
      return getPostData(req);
    })
    .then(async (postData) => {
      req.postData = postData;

      // 设置 cookie
      if (needSetCookie) {
        const expires = getCookieExpires();
        res.setHeader('Set-Cookie', `userId=${userId}; path=/; httpOnly; expires=${expires};`);
      }

      // 处理user路由
      const userData = await handlerUserRouter(req, res);
      if (userData) {
        res.end(JSON.stringify(userData));
        return;
      }

      // 处理blog路由
      const blogData = await handlerBlogRouter(req, res);
      if (blogData) {
        res.end(JSON.stringify(blogData));
        return;
      }

      // 未命中路由
      res.writeHead(404, { 'Content-type': 'text/plain' });
      res.write('404 Not Fount');
      res.end();
    })
};

module.exports = serverHandle;